package com.landscope.issue.service;

import com.landscope.issue.controller.api.dto.LoginDto;
import com.landscope.issue.controller.api.param.LoginParam;
import com.landscope.issue.controller.base.ResponseResult;
import com.landscope.issue.entity.User;
import com.landscope.issue.utils.Const;
import com.landscope.issue.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author qzp
 * @version v1.0
 * @date 2021/8/2 11:25
 **/
@Service
@Slf4j
public class ApiUserService {

    /**
     * 用户登录
     *
     * @param param:
     * @return {@link * @return com.landscope.issue.controller.base.ResponseResult<com.landscope.issue.controller.api.dto.LoginDto>}
     * @throws
     * @author 瞿子朋
     * @date 2021/8/2 14:31
     * @version v1.0
     **/
    public ResponseResult<LoginDto> login(LoginParam param) {
        // 验证access_token
        User user = TokenUtil.verifyAuthority(param.getAccessToken(), null);
        // 生成token
        String token = TokenUtil.createToken(user.getId(), user.getName(), user.getRolePermissionCode());
        log.info("登录返回token:{}",token);
        return new ResponseResult<LoginDto>().success().setData(new LoginDto(token,user.getAccount(),user.getUnitName()));
    }

    /**
     * 退出登录
     *
     * @return {@link * @return com.landscope.issue.controller.base.ResponseResult}
     * @throws
     * @author 瞿子朋
     * @date 2021/8/2 15:18
     * @version v1.0
     **/
    public ResponseResult logout() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(Const.TOKEN_KEY);
        TokenUtil.verifyToken(token);
        // 注销
        TokenUtil.logout(token);
        return new ResponseResult<LoginDto>().success().message("退出登录成功");
    }
}
